package com.yhc.order.server.service.impl;

import com.yhc.common.dto.UserCacheInfo;
import com.yhc.order.server.exception.ErrorCodeEnum;
import com.yhc.order.server.exception.OrderServiceException;
import com.yhc.order.server.service.IUserCacheService;
import org.springframework.stereotype.Service;

@Service
public class UserCacheServiceImpl implements IUserCacheService {

    private ThreadLocal<UserCacheInfo> userTl = new ThreadLocal<>();

    @Override
    public void setUser(UserCacheInfo user) {
        userTl.set(user);
    }

    @Override
    public UserCacheInfo getUser() {
        return userTl.get();
    }

    @Override
    public Long getUserId() {
        return userTl.get() == null ? null : userTl.get().getUserId();
    }

    @Override
    public Long getUserIdWithException() {
        UserCacheInfo user = userTl.get();
        if(user == null){
            throw new OrderServiceException(ErrorCodeEnum.EXCEPTION_USER_NO_LOGIN);
        }
        return user.getUserId();
    }
}
